﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common.Extensions.OrderBy;
using Common.Extensions.Where;
using DomainModel;
using EmitMapper;
using EmitMapper.MappingConfiguration;
using IManager;
using UI.JsonModel;
using WebPlatform.FiltersAndSession;
using WebPlatform.Models;

namespace WebPlatform.Controllers
{
    [CustomAuthorize]
    public class ProductController : Controller
    {

        /// <summary>
        /// 登录会话操作
        /// </summary>
        public Sessions Sessions { get; set; }

        /// <summary>
        /// 产品业务
        /// </summary>
        public IManagerProduct IMProduct { get; set; }


        /// <summary>
        /// 企业信息
        /// </summary>
        public IManagerCompany IMCompany { get; set; }

        #region 产品

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public JsonResult GetPartitions(string parentId)
        {
            var where = PredicateExtension.True<ProductPartitionInfo>();

            where = where.And(u => u.Enabled == 1 && u.ParentId == parentId);

            var list = IMProduct.LoadAll(where, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));
            var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ProductPartitionInfo, PPartitionVM>();
            var data = mapper.MapEnum(list);
            return Json(data);
        }


        IEnumerable<SelectListItem> GetFloors(string parentId, object selectedValue)
        {

            var where = PredicateExtension.True<ProductPartitionInfo>();

            where = where.And(u => u.Enabled == 1);
            if (string.IsNullOrEmpty(parentId))
            {
                where = where.And(u => u.Level == 0);
            }
            else
            {
                where = where.And(u => u.ParentId == parentId);
            }

            var list = IMProduct.LoadAll(where, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));

            list.Insert(0, new ProductPartitionInfo()
            {
                Name = "请选择......"
            });

            return new SelectList(list, "PartitionId", "Name", selectedValue);

        }


        public ActionResult Product(int Id = 0)
        {
            ProductVM product = new ProductVM();
            ObjectsMapper<ProductInfo, ProductVM> mapper =
                   ObjectMapperManager.DefaultInstance.GetMapper<ProductInfo, ProductVM>();
            if (Id > 0)
            {
                ProductInfo p = IMProduct.GetProduct(Id);
                product = mapper.Map(p);

                var partition = IMProduct.GetPartition(product.PartitionId);
                product.Children = GetFloors(partition.ParentId, product.PartitionId);
                var parentPartition = IMProduct.GetPartition(partition.ParentId);
                product.Parents = GetFloors(parentPartition.ParentId, partition.ParentId);
                product.Floors = GetFloors(null, parentPartition.ParentId);
            }
            else
            {
                product.Children = GetFloors("-1", null);
                product.Parents = GetFloors("-1", null);
                product.Floors = GetFloors(null, null);
            }

            if (string.IsNullOrEmpty(product.Image))
            {
                product.Image = "/Images/nothing.jpg";
            }

            return View(product);

        }


        [HttpPost]

        public ActionResult Product(ProductVM product)
        {
            if (ModelState.IsValid)
            {
                ObjectsMapper<ProductVM, ProductInfo> mapper =
                    ObjectMapperManager.DefaultInstance.GetMapper<ProductVM, ProductInfo>();

                var p = mapper.Map(product);
                p.PriceUnit = p.PriceUnit ?? "";
                p.IsChecked = 1;
                if (string.IsNullOrEmpty(p.Image))
                {
                    p.Image = "/Images/nothing.jpg";
                }
                if (product.Id == 0)
                {
                    var user = Sessions.User;
                    p.CompanyId = user.CompanyId;
                    p.AddUserID = user.UserID;
                    p.AddUserName = user.UserName;
                    p.AddDate = DateTime.Now;
                    p.LastModifiled = DateTime.Now;
                    try
                    {
                        IMProduct.AddProduct(p);
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                    return Json(true);
                }
                else
                {
                    p.LastModifiled = DateTime.Now;
                    try
                    {
                        IMProduct.UpdateProduct(p);
                    }
                    catch (Exception)
                    {

                        throw;
                    }

                    return Json(true);
                }

            }
            return Json(false);
        }


        [HttpPost]
        public JsonResult Products(int page = 1, int pageSize = 15)
        {

            var user = Sessions.User;
            GridData<ProductVM> data = new GridData<ProductVM>();
            ObjectsMapper<ProductInfo, ProductVM> mapper =
               ObjectMapperManager.DefaultInstance.GetMapper<ProductInfo, ProductVM>();

            var where = PredicateExtension.True<ProductInfo>();
            where = where.And(u => u.CompanyId == user.CompanyId);
            var count = IMProduct.LoadProductCount(where);

            var list = IMProduct.LoadProductAll(where, page, pageSize, new OrderByExpression<ProductInfo, DateTime>(u => u.AddDate, true));
            data.Rows = mapper.MapEnum(list).ToList();
            data.Total = count;

            return Json(data);
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteProducts(string ids)
        {
            var b = false;
            if (!string.IsNullOrEmpty(ids))
            {
                var idList = ids.Split(',');
                var list = new List<int>();
                foreach (var s in idList)
                {
                    list.Add(Convert.ToInt32(s));
                }
                b = IMProduct.DeleteProduct(list);
            }
            return Json(b);
        }

        #endregion

        #region 产品分类

        public ActionResult Partition()
        {
            return View();
        }



        [HttpPost]
        public JsonResult GridData(int page = 1, int pagesize = 10)
        {
            GridData<PPartitionVM> gridData = new GridData<PPartitionVM>();



            var p = PredicateExtension.True<ProductPartitionInfo>();
            p = p.And(u => u.Level == 0);
            var count = IMProduct.LoadCount(p);

            var lastList = GetChildren(new PPartitionVM()
            {
                HasChildren = 1,
                Level = 0
            });

            //var partition = GetChildren(lastList);

            gridData.Rows = lastList;
            gridData.Total = count;
            return Json(gridData);
        }


        /// <summary>
        /// 获取子节点
        /// </summary>
        /// <param name="partition"></param>
        /// <returns></returns>
        private IList<PPartitionVM> GetChildren(PPartitionVM partition)
        {
            var pList = new List<PPartitionVM>();
            var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ProductPartitionInfo, PPartitionVM>();
            if (partition == null || partition.HasChildren == 0)
            {
                return null;
            }
            else
            {
                var where = PredicateExtension.True<ProductPartitionInfo>();
                if (partition.PartitionId == null)
                {
                    where = where.And(w => w.Level == 0);
                }
                else
                {
                    where = where.And(w => w.ParentId == partition.PartitionId && w.Level == partition.Level + 1);
                }
                var count = IMProduct.LoadCount(where);
                var list = IMProduct.LoadAll(where, 1, count, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));

                if (list != null && list.Any())
                {
                    pList = pList.Concat(mapper.MapEnum(list)).ToList();

                    foreach (var articlePartitionInfo in pList)
                    {
                        articlePartitionInfo.children = GetChildren(articlePartitionInfo);
                    }
                }
            }
            return pList;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult OpPartition(string pId, string op)
        {

            PPartitionVM partition = new PPartitionVM();

            if (op == "edit")
            {
                var p = IMProduct.GetPartition(pId);
                var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ProductPartitionInfo, PPartitionVM>();

                partition = mapper.Map(p);

                partition.ParentName = p.ProductPartition.Name;
                partition.BEnabled = p.Enabled == 1;
                partition.BShowInt = p.ShowInt == 1;
            }
            else
            {
                var p = IMProduct.GetPartition(pId);
                if (p != null)
                {
                    partition.ParentId = p.PartitionId;
                    partition.ParentName = p.Name;
                    //partition.Roots = Roots(parentId);
                }
            }
            return View(partition);
        }


        /// <summary>
        /// 分类添加操作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OpPartition(PPartitionVM partition)
        {
            var flag = false;
            if (ModelState.IsValid)
            {
                partition.Enabled = partition.BEnabled ? 1 : 0;
                partition.ShowInt = partition.BShowInt ? 1 : 0;
                var mapper = ObjectMapperManager.DefaultInstance.GetMapper<PPartitionVM, ProductPartitionInfo>();
                var p = mapper.Map(partition);
                if (string.IsNullOrEmpty(p.PartitionId))
                {
                    flag = IMProduct.AddPartition(p);
                }
                else
                {
                    flag = IMProduct.UpdatePartition(p);
                }
            }
            return Json(flag);
        }



        /// <summary>
        /// 获取根分类
        /// </summary>
        /// <returns></returns>
        private IEnumerable<SelectListItem> Roots(string parentId)
        {
            var p = PredicateExtension.True<ProductPartitionInfo>();
            p = p.And(u => u.Enabled == 1 && u.Level == 0 && u.ParentId == parentId);

            var count = IMProduct.LoadCount(p);
            var list = IMProduct.LoadAll(p, 1, count, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));
            var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ProductPartitionInfo, PPartitionVM>();

            var partition = mapper.MapEnum(list).ToList();

            return new SelectList(partition, "PartitionId", "Name");
        }



        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string ids)
        {
            var b = false;
            if (!string.IsNullOrEmpty(ids))
            {
                IList<string> id = ids.Split(',').ToList();
                b = IMProduct.DeletePartition(id);
            }
            return Json(b);
        }


        #endregion
    }
}
